package indi.mozping.mydbpool;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author by mozping
 * @Classname MyDbPoolTest
 * @Description TODO
 * @Date 2019/2/26 17:38
 */
public class MyDbPoolTest {

    private static CountDownLatch end;
    //初始连接池的大小
    private static MyPool myPool = new MyDbPool(30);

    public static void main(String[] args) throws InterruptedException {
        //从线程数目
        int numOfThread = 50;
        end = new CountDownLatch(numOfThread);
        //每个线程获取连接的次数，总尝试获取的次数是times*numOfThread
        int times = 20;
        AtomicInteger success = new AtomicInteger();
        AtomicInteger failed = new AtomicInteger();


        for (int i = 0; i < numOfThread; i++) {
            new Thread(new MyWorker(success, failed, times), "Worker_" + i).start();
        }
        end.await();
        System.out.println("总尝试次数：" + numOfThread * times);
        System.out.println("成功次数：" + success);
        System.out.println("失败次数：" + failed);
    }

    private static class MyWorker implements Runnable {

        private AtomicInteger success;
        private AtomicInteger failed;
        private int times;

        public MyWorker(AtomicInteger success, AtomicInteger failed, int times) {
            this.success = success;
            this.failed = failed;
            this.times = times;
        }


        @Override
        public void run() {
            while (times > 0) {
                try {
                    Connection connection = myPool.getConnection(200);
                    if (connection != null) {
                        try {
                            connection.createStatement();
                            connection.commit();
                        } catch (SQLException e) {
                            e.printStackTrace();
                        } finally {
                            myPool.releaseConn(connection);
                            success.incrementAndGet();
                        }
                    } else {
                        System.out.println("线程" + Thread.currentThread().getName() + "获取连接失败!");
                        failed.incrementAndGet();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } finally {
                    times--;
                }
            }
            end.countDown();
        }
    }
}
